package com.zero.qth.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zero.common.core.domain.page.PageDomain;
import com.zero.qth.domain.Driver;
import com.zero.qth.domain.DriverBalanceDetail;
import com.zero.qth.domain.NoticeDriver;
import com.zero.qth.enums.WithdrawStatusEnum;
import com.zero.qth.service.IDriverBalanceDetailService;
import com.zero.qth.service.IDriverService;
import com.zero.qth.service.INoticeDriverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.zero.common.annotation.log.Log;
import com.zero.common.core.basecontroller.BaseController;
import com.zero.common.core.domain.result.AjaxResult;
import com.zero.common.core.enums.BusinessType;
import com.zero.qth.domain.DriverWithdraw;
import com.zero.qth.service.IDriverWithdrawService;
import com.zero.common.core.utils.poi.ExcelUtil;
import com.zero.common.core.domain.page.TableDataInfo;

import static com.qth.valet.common.utils.AmountUtil.formatAmount;

/**
 * 司机提现申请Controller
 * 
 * @author cai-xu-kun
 * @date 2025-09-17
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "司机提现申请")
@RequestMapping("/qth/driverWithdraw")
public class DriverWithdrawController extends BaseController {

    private final IDriverWithdrawService driverWithdrawService;
    private final IDriverService driverService;
    private final IDriverBalanceDetailService driverBalanceDetailService;
    private final INoticeDriverService noticeDriverService;

    @ApiOperation("修改司机提现申请")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:edit')")
    @Log(title = "司机提现申请", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        DriverWithdraw driverWithdraw = driverWithdrawService.getById(id);
        if (driverWithdraw == null) {
            return AjaxResult.error("参数异常");
        } else if (!WithdrawStatusEnum.PENDING.getCode().equals(driverWithdraw.getStatus())) {
            return AjaxResult.error("参数异常");
        }

        // 查询司机信息
        Driver driver = driverService.getById(driverWithdraw.getDriverId());
        if (driver == null) {
            return AjaxResult.error("参数异常");
        }
        if (!java.util.Objects.equals(driverWithdraw.getBankCardId(), driver.getBankCardId())) {
            return AjaxResult.error("该名司机银行卡号不一致");
        }

        if (WithdrawStatusEnum.COMPLETED.getCode().equals(status)) {
            // 修改司机的可提现金额和待提现金额
            driver.setAccountBalance(driver.getAccountBalance() - driverWithdraw.getAmount());
            driver.setWithdrawingBalance(driver.getWithdrawingBalance() - driverWithdraw.getAmount());
            driver.setIsNoticeRead(false);
            driverService.updateById(driver);

            // 插入余额明细
            DriverBalanceDetail detail = new DriverBalanceDetail();
            detail.setDriverId(driverWithdraw.getDriverId());
            detail.setWithdrawId(driverWithdraw.getId());
            detail.setAmount(driverWithdraw.getAmount());
            detail.setBalanceType(2);
            detail.setRemainingBalance(driver.getAccountBalance());
            driverBalanceDetailService.save(detail);

            // 修改状态
            driverWithdraw.setStatus(status);
            driverWithdraw.setFinishDate(new Date());
            driverWithdrawService.updateById(driverWithdraw);

            // new一个司机提现成功通知对象
            NoticeDriver noticeDriverOK = new NoticeDriver();
            noticeDriverOK.setDriverId(driverWithdraw.getDriverId());
            noticeDriverOK.setType(2);
            noticeDriverOK.setContent("成功提现" + formatAmount(driverWithdraw.getAmount()) + "元");
            noticeDriverOK.setCreateTime(new Date());
            noticeDriverService.save(noticeDriverOK);

        } else if (WithdrawStatusEnum.REJECTED.getCode().equals(status)){//拒绝提现
            // 修改司机的可提现金额和待提现金额
            driver.setWithdrawingBalance(driver.getWithdrawingBalance() - driverWithdraw.getAmount());
            driver.setIsNoticeRead(false);
            driverService.updateById(driver);

            // 修改状态
            driverWithdraw.setStatus(status);
            driverWithdrawService.updateById(driverWithdraw);
            
            //new一个司机提现失败的通知对象
            NoticeDriver noticeDriverNG = new NoticeDriver();
            noticeDriverNG.setDriverId(driverWithdraw.getDriverId());
            noticeDriverNG.setType(8);
            noticeDriverNG.setContent(formatAmount(driverWithdraw.getAmount()) + "元提现失败");
            noticeDriverNG.setCreateTime(new Date());
            noticeDriverService.save(noticeDriverNG);
        }

        return AjaxResult.success("提现处理完成");
    }

    /*=========================================================================*/


    /**
     * 查询司机提现申请分页
     */
    @ApiOperation("查询司机提现申请分页")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:list')")
    @GetMapping("/list")
    public TableDataInfo list(DriverWithdraw driverWithdraw) {
        PageDomain pageDomain = this.startPage();
        Page<DriverWithdraw> p = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<DriverWithdraw> page = driverWithdrawService.selectDriverWithdrawListPage(driverWithdraw, p);
        return this.getDataTable(page);
    }

    /**
     * 导出司机提现申请列表
     */
    @ApiOperation("导出司机提现申请列表")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:export')")
    @Log(title = "司机提现申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DriverWithdraw driverWithdraw) {
        List<DriverWithdraw> list = driverWithdrawService.selectDriverWithdrawList(driverWithdraw);
        ExcelUtil<DriverWithdraw> util = new ExcelUtil<DriverWithdraw>(DriverWithdraw.class);
        util.exportExcel(response, list, "司机提现申请数据");
    }

    /**
     * 获取司机提现申请详细信息
     */
    @ApiOperation("获取司机提现申请详细信息")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(driverWithdrawService.selectDriverWithdrawById(id));
    }

    /**
     * 新增司机提现申请
     */
    @ApiOperation("新增司机提现申请")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:add')")
    @Log(title = "司机提现申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DriverWithdraw driverWithdraw) {
        return toAjax(driverWithdrawService.insertDriverWithdraw(driverWithdraw));
    }

    /**
     * 修改司机提现申请
     */
    @ApiOperation("修改司机提现申请")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:edit')")
    @Log(title = "司机提现申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DriverWithdraw driverWithdraw) {
        return toAjax(driverWithdrawService.updateDriverWithdraw(driverWithdraw));
    }

    /**
     * 删除司机提现申请
     */
    @ApiOperation("删除司机提现申请")
    @PreAuthorize("@ss.hasPermi('qth:driverWithdraw:remove')")
    @Log(title = "司机提现申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(driverWithdrawService.deleteDriverWithdrawByIds(ids));
    }
}
